package com.jx.lcs.product.web;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jx.lcs.product.entity.ProductInfo;
import com.jx.lcs.product.entity.ProductType;
import com.jx.lcs.product.service.ProductService;
import com.jx.lcs.product.service.ProductTypeService;
import com.jx.lcs.util.common.CharUtil;
import com.jx.lcs.util.common.GetProp;
import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.persistence.PropertyFilter;
import com.tianyu.jty.common.utils.DateUtils;
import com.tianyu.jty.common.web.BaseController;

/** 
 * 产品controller
 * @author JiaYY 
 * @date 2015年7月2日
 */
@Controller
@RequestMapping("product")
public class ProductController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductTypeService productTypeService;
	
	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "product/productList";
	}
	
	/**
	 * 获取产品列表json
	 */
	@RequestMapping(value="json",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> productList(HttpServletRequest request) {
		try{
			Page<ProductInfo> page = getPage(request);
			List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
			page = productService.search(page, filters);
			return getEasyUIData(page);
		}catch(Exception e){
			logger.error("--获取产品列表出现异常！", e);
			return null;
		}
	}
	
	/**
	 * 添加产品跳转
	 * 
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("product", new ProductInfo());
		model.addAttribute("action", "create");
		return "product/productForm";
	}

	/**
	 * 添加产品
	 * 
	 * @param product
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(@Valid ProductInfo product, Model model) {
		try{
			ProductInfo productInfo = productService.findByPCode(product.getPcode().trim());
			if(productInfo != null) {
				return "该产品编码已存在";
			}
			if ("".equals(product.getId()))
				product.setId(null);
			
			String pname = product.getPname().trim();
			pname = CharUtil.charConvert(pname);
			product.setPname(pname);
			product.setPcode(product.getPcode().trim());
			product.setOrderOverTime(0);
			product.setSmsRemaindTime(0);
			product.setRecordTime(DateUtils.getSysDate());
			if(product.getProductType() != null && !"".equals(product.getProductType())) {
				ProductType productType = productTypeService.findEntityByTypeCode(product.getProductType());
				product.setPtcode(productType);
			}
			productService.save(product);
			
			return "success";
		}catch(Exception e){
			logger.error("--添加产品出现异常！！", e);
			
			return "添加产品失败";
		}
		
	}

	/**
	 * 修改产品跳转
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") String id, Model model) {
		model.addAttribute("product", productService.get(id));
		model.addAttribute("action", "update");
		return "product/productForm";
	}

	/**
	 * 修改产品
	 * 
	 * @param product
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute @RequestBody ProductInfo product,Model model) {
		try{
			ProductInfo info = productService.get(product.getId());
			if(info != null) {
				String pname = product.getPname().trim();
				pname = CharUtil.charConvert(pname);
				
				info.setPname(pname);
				info.setPcode(product.getPcode().trim());
				info.setInvestPeriod(product.getInvestPeriod());
				info.setPeriodUnit(product.getPeriodUnit());
				info.setTotalMoney(product.getTotalMoney());
				info.setHotStatus(product.getHotStatus());
				info.setBeginAgentDay(product.getBeginAgentDay());
				info.setEndPaymentDay(product.getEndPaymentDay());
				info.setStepLength(product.getStepLength());
				info.setAgentUserNum(product.getAgentUserNum());
				info.setMinBuyMoney(product.getMinBuyMoney());
				info.setDetailUrl(product.getDetailUrl());
				info.setShareUrl(product.getShareUrl());
				
				//根据结束日期，设置产品是否售罄
				if("1".equals(info.getFullStatus()) && (info.getEndPaymentDay().getTime() > DateUtils.getSysDate().getTime())) {
					info.setFullStatus("0");
				} else if("0".equals(info.getFullStatus()) && ((info.getEndPaymentDay().getTime() + 24*60*60*1000) < DateUtils.getSysDate().getTime())) {
					info.setFullStatus("1");
				}
				
				productService.update(info);
				
			}
			
			return "success";
		}catch(Exception e){
			logger.error("--修改产品出现异常！！", e);
			
			return "修改产品失败";
		}
	}

	/**
	 * 删除产品
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id) {
		productService.delete(id);
		return "success";
	}
	
	@ModelAttribute
	public void getGoods(@RequestParam(value = "id", defaultValue = "-1") String id,Model model) {
		if (id != null && !"".equals(id)) {
			model.addAttribute("product", productService.get(id));
		}
	}
	
	/**
	 * 发布产品
	 * 
	 * @return
	 */
	@RequestMapping(value = "publish/{id}")
	@ResponseBody
	public String update(@PathVariable("id") String id) {
		try{
			ProductInfo info = productService.get(id);
			if(info != null) {
				info.setPublishStatus("1");
				info.setRecordTime(DateUtils.getSysDate());
				
				productService.update(info);
			}
			return "success";
		}catch(Exception e){
			logger.error("--发布产品出现异常！！", e);
			
			return "发布产品失败";
		}
	}
	
	/**
	 * 图片跳转
	 */
	@RequestMapping(value = "upload/{id}", method = RequestMethod.GET)
	public String uploadForm(@PathVariable("id") String id, Model model) {
		model.addAttribute("id", id);
		model.addAttribute("action", "upload");
		return "product/productUpload";
	}
	
	/**
	 * 图片上传
	 * 
	 * @param ctx
	 * @throws IOException
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam MultipartFile img, String id,
			HttpServletRequest request, HttpServletResponse response) {
		String path = GetProp.getConfig("PRODUCT_IMG_UPLOAD_PATH");
		Long tm = System.currentTimeMillis();
		String fileName = img.getOriginalFilename();
		fileName = tm + fileName.substring(fileName.lastIndexOf("."));
		if (!StringUtils.isBlank(fileName)) {
			// 保存
			try {
				File targetFile = new File(path, fileName);
				if (targetFile.exists()) {
					targetFile.delete();
				}
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				img.transferTo(targetFile);
				
				ProductInfo product = productService.get(id);
				product.setImgUrl(GetProp.getConfig("PRODUCT_IMG_SERVER_URL") + fileName);
				productService.update(product);
			} catch (Exception e) {
				logger.error("上传产品图片异常:", e);
			}
		}
		return "success";
	}
}
